package com.eet.rabbitmq.direct;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 消费者
 *
 * @author zheng.zhang
 */
@SuppressWarnings("all")
public class Consumer implements Runnable {
    private static final Runnable RUNNABLE = new Consumer();

    public static void main(String[] args) {
        new Thread(RUNNABLE, "queue4").start();
        new Thread(RUNNABLE, "queue5").start();
        new Thread(RUNNABLE, "queue6").start();
    }

    @Override
    public void run() {
        final ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("www.eet.ink");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("/");

        try (final Connection connection = factory.newConnection();
             final Channel channel = connection.createChannel()) {
            String queueName = Thread.currentThread().getName();
            channel.basicConsume(queueName, true, new DeliverCallback() {
                @Override
                public void handle(String consumerTag, Delivery message) throws IOException {
                    System.out.println(queueName + "收到的消息是: " + new String(message.getBody(), StandardCharsets.UTF_8));
                }
            }, new CancelCallback() {
                @Override
                public void handle(String consumerTag) throws IOException {
                    System.out.println("消息发送失败!");
                }
            });

            System.out.println("消息接收完成!");
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
